//
//  HMNetWorkTool.m
//  HowToDo
//
//  Created by 胡坤 on 2017/1/3.
//  Copyright © 2017年 KY. All rights reserved.
//

#import "HMNetWorkTool.h"
#import <SMS_SDK/SMSSDK.h>

#ifdef __DeBug__

#define BaseUrlString @"http://iosapi.itcast.cn:8080/"

#else

#define BaseUrlString  @"http://howtodo.besttoptoday.com"

#endif


@implementation HMNetWorkTool


//单例实例化对象的方法
+ (instancetype)sharedTool;
{
    static HMNetWorkTool*instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HMNetWorkTool alloc]initWithBaseURL:[NSURL URLWithString:BaseUrlString]];
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"text/html",@"text/javascript",@"text/xml", nil];
        
    });
    return instance;
}
//普通网络请求；
-(void)requestType:(RequestType)type UrlString:(NSString*) urlString Parameter:(id)para Finished:(void(^)(id responseObject))finishedBlock  Progress:(void(^)(NSProgress* progress))progressBlock  Failed:(void(^)(NSError * _Nonnull error))failedBlock
{
    
    void(^success)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)  = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        finishedBlock(responseObject);
    };
    
    void(^failure)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        failedBlock(error);
    };
    void(^progress)(NSProgress * _Nonnull Progress) = ^(NSProgress * _Nonnull Progress)
    {
//添加progressBlock的安全判断 Stan
        if (progressBlock != nil) {
            progressBlock(Progress);

        }
    };
    
    
    if (type == HTDGET)
    {
        
        [self GET:urlString parameters:para progress:progress success:success failure:failure];
        
    }else if (type == HTDPOST)
    {
        [self POST:urlString parameters:para progress:progress success:success failure:failure];
    }
}


//获取榜单列表详情数据
- (void)requestToplistDetailBySeriesid:(NSInteger)seriesId andFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock{
    
    NSDictionary *parmas = @{@"id":@(seriesId)};

    [self requestType:HTDGET UrlString:@"app/series/getSeriesListById" Parameter:parmas Finished:completedBlock Progress:nil Failed:failedBlock];
    

}

//获取榜单列表数据
- (void)requestHomeToplistDataFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock{
    
    [self requestType:HTDGET UrlString:@"app/resource/getSeriesList" Parameter:nil Finished:completedBlock Progress:nil Failed:failedBlock];
}

//获取十万个为什么、土豪专享Cell数据
- (void)requestRecommendDetailDataWithDetailID:(NSInteger)detailID andFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock{
    
    NSDictionary *parmas = @{@"id":@(detailID)};
    [self requestType:HTDGET UrlString:@"app/audio/getAudioDetailById" Parameter:parmas Finished:completedBlock Progress:nil Failed:failedBlock];
    
}

//获取十万个为什么、土豪专享数据
- (void)requestRecommendJsonDataWithType:(NSInteger)type andOrderBy:(NSString *)orderType andPage: (NSInteger)page andFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock{
    
    NSDictionary *params = [NSDictionary dictionary];
    if (type == 0) {
      params = @{
                                 @"type": @(type),
                                 @"orderby": orderType,
                                 @"page": @(page)
                                 };
        
    } else {
        
      params = @{
                @"orderby": orderType,
                @"page": @(page)
                                            };
    }
    
    [self requestType:HTDGET UrlString:@"app/resource/getResourceListByType" Parameter:params Finished:completedBlock Progress:nil Failed:failedBlock];
}

//获取首页数据
-(void)requestHomeJsonDataFinished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [[HMNetWorkTool sharedTool]requestType:HTDGET UrlString:@"app/home/getHomeData?token=" Parameter:nil Finished:finishedBlock Progress:nil Failed:failedBlock];
}



//获取推荐界面数据
-(void)requestRecommendJsonDataFinished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [[HMNetWorkTool sharedTool]requestType:HTDGET UrlString:@"app/resource/getSubscribeList" Parameter:nil Finished:^(id responseObject)
     {
         finishedBlock(responseObject);
     } Progress:nil Failed:^(NSError * _Nonnull error)
     {
         failedBlock(error);
     }];
}

// 获取随身听的音频列表数据
- (void)requestListenAnyTimeResJasonDataWithTimeLen:(NSString *)time andFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock{
    
    // @"token": token
    NSDictionary *params = @{
                             @"time_len": time
                             };
    
    [self requestType:HTDGET UrlString:@"app/resource/getAnyTimeListenResList" Parameter:params Finished:completedBlock Progress:nil Failed:failedBlock];
}


- (void)isWiFiSuccessBlock:(void(^)(NSInteger state))successBlock{
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];

    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        // 当网络状态改变了, 就会调用这个block
        switch
        (status) {
            case
            AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
            case
            AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                break;
            case
            AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
            case
            AFNetworkReachabilityStatusReachableViaWiFi: // WIFI -- 2
                NSLog(@"WIFI");
            {
                if (successBlock) {
                    successBlock(2);
                }
            }
                break;
        }
    }];
    // 3.开始监控
    [mgr startMonitoring];
    
}
     
-(void)requestTodayHappyTalkJsonDataFinished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock {
    [[HMNetWorkTool sharedTool]requestType:HTDGET UrlString:@"app/resource/getEverydayBookList" Parameter:nil Finished:^(id responseObject)

     {
         finishedBlock(responseObject);
     } Progress:nil Failed:^(NSError * _Nonnull error)
     {
         failedBlock(error);
     }];
}


//获取达人详情界面数据
-(void)requestDetailsJsonDataWithID:(NSNumber *)tid Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [self requestType:HTDGET UrlString:[NSString stringWithFormat:@"app/specialColumn/getDetailById?id=%zd&token=c258521d2c7948ab82edfc30fc8849aa", tid.intValue] Parameter:nil Finished:^(id responseObject)
     {
         finishedBlock(responseObject);
     } Progress:nil Failed:^(NSError * _Nonnull error)
     {
         failedBlock(error);
     }];
}

//获取春花界面 数据
-(void)requestSpringFlowersJsonDataWithType:(NSInteger)type Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    NSDictionary *parme = @{
                            @"id":@(type)
                            };
    [[HMNetWorkTool sharedTool] requestType:HTDGET UrlString:@"app/specialColumn/getItemListById" Parameter:parme Finished:^(id responseObject) {
        
        finishedBlock(responseObject);
        
        
    } Progress:nil Failed:^(NSError * _Nonnull error) {
       
        NSLog(@"%@",error);
        
    }];
}

//金句数据
-(void)requestGoldSentenceWithType:(RequestType)type Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [self requestType:HTDGET UrlString:@"app/resource/getBookSentenceList" Parameter:nil Finished:finishedBlock Progress:nil Failed:failedBlock];

}

//获取试读界面数据
-(void)requestTryReadJsonDataWithID:(NSNumber *)tid Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [self requestType:HTDGET UrlString:[NSString stringWithFormat:@"app/specialColumn/getItemListById?id=%zd&is_probation=1&token=cf40f0fd9cea4e7a92ed1d414479df92", tid.intValue] Parameter:nil Finished:^(id responseObject)
     {
         finishedBlock(responseObject);
     } Progress:nil Failed:^(NSError * _Nonnull error)
     {
         failedBlock(error);
     }];
}

//天天长知识二级详情列表
-(void)requestFreeAudioFinished:(void(^)(id responseObject))completedBlock Failed:(void(^)(NSError* error))failedBlock
{
    NSDictionary* para = @{@"page":@1,
                           @"pageSize":@20};
    
    [self requestType:HTDGET UrlString:@"app/resource/getFreeAudioList" Parameter:para Finished:completedBlock Progress:nil Failed:failedBlock];
}




//获取搜索数据
-(void)requestSearchResultJsonDataWithStr:(NSString *)str Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock {
    
    NSDictionary *parameter = @{
                                @"key_word" : str
                                };
    [self requestType:HTDGET UrlString:@"app/resource/searchRes" Parameter:parameter Finished:^(id responseObject) {
        
        finishedBlock(responseObject);
    } Progress:nil Failed:^(NSError * _Nonnull error) {
        failedBlock(error);
    }];
    
}





- (void)requstRegisterPhoneNum:(NSString *)phoneNum password:(NSString *)password Finished:(void (^)(id))finishedBlock Failed:(void (^)(NSError *))failedBlock{
    NSDictionary *parameter = @{
                                @"token" : @"726d784a46194e75981b41ff8ccb5770",
                                @"password" : password,
                                @"phone_num" : phoneNum
                                };
    NSString *registUrl = @"app/user/phoneUserRegister";
    
    [self requestType:HTDPOST UrlString:registUrl Parameter:parameter Finished:^(id responseObject) {
        
        finishedBlock(responseObject);
    } Progress:nil Failed:^(NSError * _Nonnull error) {
        failedBlock(error);
    }];
}

//登录
- (void)requstLoginPhoneNum:(NSString *)phoneNum password:(NSString *)password andToken:(NSString *)token Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock{
    NSString *loginUrl = @"app/user/phoneUserLogin";
    NSDictionary *parameter = @{
                                @"token" : token,
                                @"password" : password,
                                @"phone_num" : phoneNum
                                };
    
    [self requestType:HTDPOST UrlString:loginUrl Parameter:parameter Finished:^(id responseObject) {
        finishedBlock(responseObject);
    } Progress:nil Failed:^(NSError * _Nonnull error) {
        failedBlock(error);
    }];
    
}

//修改密码
- (void)requstChangePhoneNum:(NSString *)newPassword andOldPassword:(NSString *)oldPassword andToken:(NSString *)token Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock{
    NSString *changeUrl = @"app/user/changeUserPsw";
    NSDictionary *parameter = @{
                                @"token" : token,
                                @"old_psw" : oldPassword,
                                @"new_psw" : newPassword
                                };
    [self requestType:HTDPOST UrlString:changeUrl Parameter:parameter Finished:^(id responseObject) {
        
        finishedBlock(responseObject);
    } Progress:nil Failed:^(NSError * _Nonnull error) {
        failedBlock(error);
        
    }];
    
}


//获取验证码
- (void)requstCodeNum:(NSString *)phoneNum Finished:(void (^)(id))finishedBlock Failed:(void (^)(NSError *))failedBlock{
    
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:phoneNum zone:@"86" customIdentifier:nil result:^(NSError *error) {
        
        if (!error) {
            //正确
            
        }else{
            failedBlock(error);
        }
        
    }];
    
    
}

//提交验证码
- (void)requstCommitCode:(NSString *)codeNum andPhoneNum:(NSString *)phoneNum Finished:(void (^)(id))finishedBlock Failed:(void (^)(NSError *))failedBlock{
    
    [SMSSDK commitVerificationCode:codeNum phoneNumber:phoneNum zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
        
        {
            if (!error)
            {
                
                
                
            }
            else
            {
                failedBlock(error);
                NSLog(@"错误信息:%@",error);
            }
        }
    }];
    
}


//1.0 版本首页数据请求接口
/*
 *@prama : parameter 请求参数
 **/
-(void)requestHomeJsonDataWithParameter:(id)parameter Finished:(void(^)(id responseObject))finishedBlock Failed:(void(^)(NSError* error))failedBlock
{
    [[HMNetWorkTool sharedTool]requestType:HTDGET UrlString:@"app/home/getHomeData" Parameter:parameter Finished:finishedBlock Progress:nil Failed:failedBlock];
}


- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType andShareMessage: (NSString *)shareMessage
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = shareMessage;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}


- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        
        
    }];

}
@end
